<?php

namespace App\Library\Logic;

use App\Models\ShopOrderGoodsModel;
use Illuminate\Database\Eloquent\Model;

class ShopOrderGoodsLogic extends ShopOrderGoodsModel
{
    /**
     * limitBuy
     * @param int $specId
     * @return int
     */
    public static function limitBuy(int $specId): int
    {
        return self::query()->leftJoin('shop_order', 'shop_order.order_id', 'shop_order_goods.order_id')
            ->where('buy_user_id', USERID)
            ->where('order_buy_status', '<>', 3)
            ->where('spec_id', $specId)->count();
    }

    /**
     * createData
     * @param int $quantity
     * @param Model $v
     * @return array|string
     */
    public static function createData(int $quantity, Model $v): array|string
    {
        $discountSpecial = bcsub($v->ps_price_underlined, $v->special_price, 2);
        $discount = bcadd($discountSpecial, $v->sub_price, 2);
        return [
            'sellerId' => $v->user_id,
            'productFileId' => $v->product_avatar ?? '',
            'specFileId' => $v->ps_avatar ?? '',
            'productId' => $v->product_id,
            'specId' => $v->ps_id,
            'title' => $v->product_name ?? '',
            'spec' => $v->ps_name ?? '',
            'quantity' => $quantity,
            'originalPrice' => $v->ps_price_underlined,
            'specialPrice' => $v->special_price,
            'price' => bcsub($v->ps_price_underlined, $discount, 2),
            'discount' => $discount,
            'discountSpecial' => $discountSpecial,
            'discountSub' => $v->sub_price,
            'psUsableStock' => $v->ps_usable_stock,
        ];
    }

    /**
     * add
     * @param array $data
     * @param int $orderId
     * @return void
     */
    public static function add(array $data, int $orderId): void
    {
        foreach ($data as $v) {
            $v['orderId'] = $orderId;
            $product = ShopProductLogic::detail($v['productId']);
            $product->specInfo = ProductSpecLogic::detail($v['specId']);
            $v['info'] = $product;
            self::insertForModel($v);
        }
    }

    /**
     * plug
     * @param Model $product
     * @param Model $spec
     * @param Model $order
     * @return void
     */
    public static function plug(Model $product, Model $spec, Model $order): void
    {
        $product->specInfo = $spec;
        self::insertForModel([
            'orderId' => $order->order_id,
            'sellerId' => $product->user_id,
            'productFileId' => $product->product_avatar,
            'specFileId' => $spec->ps_avatar,
            'productId' => $product->product_id,
            'specId' => $spec->ps_id,
            'title' => $product->product_name,
            'spec' => $spec->ps_name,
            'originalPrice' => $order->pay_price,
            'specialPrice' => $order->pay_price,
            'price' => $order->pay_price,
            'info' => $product,
        ]);
    }
}
